package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

var Secret = []byte("helloWord")
var LocalExpireTime = 3 * time.Hour

type Claims struct {
	UserId   int    `json:"user_id"`
	UserName string `json:"user_name"`
	Avatar   string `json:"avatar"`
	jwt.StandardClaims
}

func GenerateToken(userId int, username, avatar, issuer string) (string, error) {
	nowTime := time.Now()                      //当前时间
	expireTime := nowTime.Add(LocalExpireTime) //有效时间

	claims := Claims{
		userId,
		username,
		avatar,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    issuer,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(Secret)
	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return Secret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}
